package com.example.psychologicalappointmentsystem.Controller;

import com.example.psychologicalappointmentsystem.Entity.User;
import com.example.psychologicalappointmentsystem.Entity.UserQuestionnaireSummary;
import com.example.psychologicalappointmentsystem.Enum.QualificationStatus;
import com.example.psychologicalappointmentsystem.Enum.UserRole;
import com.example.psychologicalappointmentsystem.JpaRepository.UserQuestionnaireSummaryRepository;
import com.example.psychologicalappointmentsystem.JpaRepository.UserRepository;
import com.example.psychologicalappointmentsystem.Object.UserLoginRequest;
import com.example.psychologicalappointmentsystem.Object.UserRegistrationRequest;
import com.example.psychologicalappointmentsystem.Response.JWTResponse;
import com.example.psychologicalappointmentsystem.service.UserService;
import com.example.psychologicalappointmentsystem.tools.JWTUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/api/user")  // 处理用户相关请求的控制器，所有路径以 "/api/user" 开头
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserQuestionnaireSummaryRepository userQuestionnaireSummaryRepository;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private JWTUtils jwtUtils;

    @Autowired
    private UserService userService;


    @PostMapping("/register")  // 处理用户注册请求
    public ResponseEntity<?> registerUser(@RequestParam String username,
                                          @RequestParam String password,
                                          @RequestParam String email,
                                          @RequestParam String region,
                                          @RequestParam UserRole role,
                                          @RequestParam(required = false) MultipartFile file) {
        // 检查用户角色，来访者直接注册，咨询师需要上传资质证明,
        if (role== UserRole.CONSULTANT && file==null ) {
            return ResponseEntity.badRequest().body("咨询师必须上传资质证明！");
        }
        if(userRepository.existsByUsername(username)){
            return ResponseEntity.badRequest().body("此用户已存在");
        }

        // 加密密码
        String encodedPassword = bCryptPasswordEncoder.encode(password);

        // 创建用户对象并保存到数据库
        User user = new User();
        user.setUsername(username);
        user.setPassword(encodedPassword);
        user.setEmail(email);
        user.setRegion(region);
        user.setRole(role);
        if (role!=UserRole.CONSULTANT){
            user.setStatus(QualificationStatus.APPROVED);
            userRepository.save(user);
            return ResponseEntity.ok("用户注册成功.");
        }else{
            String filePath = uploadQualificationImage(file);
            user.setQualificationImage(filePath);
            user.setStatus(QualificationStatus.PENDING);
            userRepository.save(user);
        }
        return ResponseEntity.ok("咨询师注册成功，等待审核中...");
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody UserLoginRequest loginRequest) {

        // 根据用户名查询用户
        User foundUser = userRepository.findByUsername(loginRequest.getUsername());
        if (foundUser == null || !bCryptPasswordEncoder.matches(loginRequest.getPassword(), foundUser.getPassword())){
            return ResponseEntity.badRequest().body("用户名或密码无效");
        }
        UserQuestionnaireSummary userQuestionnaireSummary = userQuestionnaireSummaryRepository.find1UserId(foundUser.getId());
        // 如果是来访者，直接登录
        if (foundUser.getRole() == UserRole.VISITOR) {
            String token = jwtUtils.generateToken(foundUser);
            //将token写到数据库中
            foundUser.setToken(token);
            userRepository.save(foundUser);
            // 初始化来访者首次登录问卷记录
            if (userQuestionnaireSummary==null){
                UserQuestionnaireSummary initial = new UserQuestionnaireSummary();
                initial.setUserId(foundUser.getId());
                initial.setIsCompleted(0);
                userQuestionnaireSummaryRepository.save(initial);
                userQuestionnaireSummary = userQuestionnaireSummaryRepository.find1UserId(foundUser.getId());
            }
            return ResponseEntity.ok(new JWTResponse(foundUser.getId(),token,foundUser.getRole(),userQuestionnaireSummary.getIsCompleted()));
        }
        // 如果是咨询师，判断资质审核状态
        if (foundUser.getRole() == UserRole.CONSULTANT) {
            if (foundUser.getStatus() == QualificationStatus.PENDING) {
                return ResponseEntity.status(10086).body("咨询师资质审核中，请耐心等待...");
            }
            if (foundUser.getStatus() == QualificationStatus.REJECTED) {
                return ResponseEntity.badRequest().body("咨询师资质审核被拒绝，请重新上传资质证明进行注册...");
            }
            // 审核通过的咨询师生成Token
            String token = jwtUtils.generateToken(foundUser);
            //将token写到数据库中
            foundUser.setToken(token);
            userRepository.save(foundUser);
            //返回
            return ResponseEntity.ok(new JWTResponse(foundUser.getId(),token,foundUser.getRole(),0));
        }
        return ResponseEntity.badRequest().body("登录失败，请重试！");
    }
    // 处理文件上传
    private String uploadQualificationImage(MultipartFile file) {
        try {
            // 获取文件名
            String filename = file.getOriginalFilename();

            // 获取用户根目录
            String userHome = System.getProperty("user.home");  // 获取当前用户的根目录

            // 定义保存文件的目录路径
            String uploadDir = userHome + "/uploads/qualification/";  // 目标文件夹

            // 创建目录（如果目录不存在的话）
            File directory = new File(uploadDir);
            if (!directory.exists()) {
                directory.mkdirs();  // 如果目录不存在，则创建它
            }
            // 创建目标文件
            File dest = new File(uploadDir + filename);

            // 将文件保存到目标路径
            file.transferTo(dest);  // 保存文件

            // 返回文件相对路径
            return dest.getPath();  // 返回相对路径用于保存到数据库
        } catch (IOException e) {
            e.printStackTrace();
            return null;  // 上传失败返回 null
        }
    }

    @ApiOperation("获取当前用户信息")
    @RequestMapping(value = "/info", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public ResponseEntity<?> userInfo() {
        return userService.userInfo();
    }

    @ApiOperation("修改用户信息")
    @RequestMapping(value = "/infoUpdate", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public ResponseEntity<?> userInfoUpdate(@RequestBody  UserLoginRequest loginRequest) {
        return userService.userInfoUpdate(loginRequest);
    }

    @ApiOperation("获取咨询师列表")
    @ApiImplicitParams({
            // 分页
            @ApiImplicitParam(name = "current", value = "查询页码", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "pageSize", value = "页数据量", dataType = "Integer", dataTypeClass = Integer.class)
    })
    @RequestMapping(value = "/consultation/list/page", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public ResponseEntity<?> consultationList(@RequestBody UserLoginRequest loginRequest) {
        return userService.userListPage(loginRequest);
    }

    @ApiOperation("头像上传的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "头像文件", required = true, dataType = "MultipartFile", dataTypeClass = MultipartFile.class),
    })
    @RequestMapping(value = "/image/upload", method = RequestMethod.POST)
    public ResponseEntity<?> consultationList(@RequestParam("file") MultipartFile file) {
        return userService.userHeadImageUpload(file);
    }

}

